package com.example.javaee.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.javaee.Util.CommunityUtil;
import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import com.example.javaee.exception.LoginException;
import com.example.javaee.exception.RegisterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;


import java.util.*;

import java.util.List;
import java.util.Random;


@Service
public class RegisterService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    public String sendEmail(String email) throws RegisterException {
        if(isEmailExisted(email)){
            throw new RegisterException("此邮箱已被注册!");
        }
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("激活邮件");
        message.setText("验证码为"+checkCode);
        javaMailSender.send(message);
        return checkCode;
    }

    public void setUserInfo(User user) throws LoginException {
        if(user.getUsername().equals("")){
            throw new LoginException("请输入用户名!");
        }
        if(user.getPassword().equals("")){
            throw new LoginException("请输入密码");
        }
        if(isUsernameExisted(user.getUsername())){
            throw new LoginException("用户名重复!请更换用户名");
        }
        // salt
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        // 加盐加密
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        // 默认未激活
        user.setStatus(0);
        user.setType(0);
        TimeZone time = TimeZone.getTimeZone("Etc/GMT-8");  //转换为中国时区
        TimeZone.setDefault(time);
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }
    public boolean isUsernameExisted(String username){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        List<User> result;
        result = userMapper.selectList(lqw);
        return result.size() == 1;
    }

    public boolean isEmailExisted(String email){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail,email);
        List<User> result;
        result = userMapper.selectList(lqw);
        return result.size() >= 1;
    }
}
